/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.Fpry;
import me.zhengjie.business.domain.Qy;
import me.zhengjie.business.domain.Zhsq;
import me.zhengjie.business.domain.sup.Rygl;
import me.zhengjie.business.repository.QyRepository;
import me.zhengjie.business.repository.ZhsqRepository;
import me.zhengjie.business.service.RyglService;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.FpryRepository;
import me.zhengjie.business.service.FpryService;
import me.zhengjie.business.service.dto.FpryDto;
import me.zhengjie.business.service.dto.FpryQueryCriteria;
import me.zhengjie.business.service.mapstruct.FpryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.persistence.DiscriminatorValue;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-06-16
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class FpryServiceImpl implements FpryService {

    private final FpryRepository fpryRepository;
    private final ZhsqRepository zhsqRepository;
    private final QyRepository qyRepository;
    private final FpryMapper fpryMapper;

    @Autowired
    private final RyglService ryglService;

    @Override
    public Map<String,Object> queryAll(FpryQueryCriteria criteria, Pageable pageable){
        Page<Fpry> page = fpryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fpryMapper::toDto));
    }

    @Override
    public List<FpryDto> queryAll(FpryQueryCriteria criteria){
        return fpryMapper.toDto(fpryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public FpryDto findById(String bisFpryId) {
        Fpry fpry = fpryRepository.findById(bisFpryId).orElseGet(Fpry::new);
        ValidationUtil.isNull(fpry.getBisFpryId(),"Fpry","bisFpryId",bisFpryId);
        return fpryMapper.toDto(fpry);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FpryDto create(Fpry resources) {
        resources.setBisFpryId(IdUtil.simpleUUID()); 
        return fpryMapper.toDto(fpryRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(List<Long> selectedZhids,List<Long> selectedPgrys, String ywlx) {
        log.info("FpryServiceImpl create selectedZhids : {}", selectedZhids);
        log.info("FpryServiceImpl create selectedPgrys : {}", selectedPgrys);
        log.info("FpryServiceImpl create ywlx : {}", ywlx);
        Date date = new Date();
        for (Long zhid : selectedZhids) {
            if("qy".equals(ywlx)) {
                Qy qy = qyRepository.queryByBisQyZhsqIdAndBisGsglIszf(zhid, "1");
                qy.setBisQyZt("qygl02");
                qyRepository.save(qy);
                fpryRepository.updateFpryZt(zhid);
            } else if("pg".equals(ywlx)) {
                Zhsq zhsq = zhsqRepository.findById(zhid).orElseGet(Zhsq::new);
                zhsq.setBisZhsqZt("02");
                zhsqRepository.save(zhsq);
                fpryRepository.updateFpryZt(zhid);
            } else {
                fpryRepository.updateFpryZt(zhid);
            }
            for (Long pgryid : selectedPgrys) {
                Rygl rygl = ryglService.findByBisRyglUserId(pgryid);
                log.info("分配人员 : {}, userId:{}, rygl {}", rygl.getBisRyglXm(), rygl.getBisRyglUserId(), rygl.getBisRyglRylx());
                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(zhid);
                fpry.setBisFpryRyglId(pgryid);
                fpry.setBisFpryRyglXm(rygl.getBisRyglXm());
                fpry.setBisFpryFpsj(date);
                fpry.setBisFpryZt("0");
                fpry.setBisFpryRylx(rygl.getBisRyglRylx());
                fpryRepository.save(fpry);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Fpry resources) {
        Fpry fpry = fpryRepository.findById(resources.getBisFpryId()).orElseGet(Fpry::new);
        ValidationUtil.isNull( fpry.getBisFpryId(),"Fpry","id",resources.getBisFpryId());
        fpry.copy(resources);
        fpryRepository.save(fpry);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisFpryId : ids) {
            fpryRepository.deleteById(bisFpryId);
        }
    }

    @Override
    public void download(List<FpryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FpryDto fpry : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("主键ID", fpry.getBisFpryId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}